﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WindowsService
{
    public partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
            _Timer.Elapsed += _Timer_Elapsed;
            _Timer.Interval = 5000;
            _Timer.AutoReset = true;
            _Timer.Enabled = false;
        }

        private void _Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _Timer.Stop();
            if (ReleasePort(21) > 0)
            {
                _Timer.Enabled = false;
            }
            else
            {
                _Timer.Start();
            }


        }

        System.Timers.Timer _Timer = new System.Timers.Timer();
        protected override void OnStart(string[] args)
        {
            _Timer.Start();
        }

        protected override void OnStop()
        {
            _Timer.Stop();
        }

        /// <summary>
        /// 释放端口
        /// </summary>
        /// <param name="port"></param>
        int ReleasePort(int port)
        {
            int result = 0;
            Process _Process = new Process();
            // 设置命令行、参数
            _Process.StartInfo.FileName = "cmd.exe";
            _Process.StartInfo.UseShellExecute = false;
            _Process.StartInfo.RedirectStandardInput = true;
            _Process.StartInfo.RedirectStandardOutput = true;
            _Process.StartInfo.RedirectStandardError = true;
            _Process.StartInfo.CreateNoWindow = true;

            // 启动CMD
            _Process.Start();
            // 运行端口检查命令
            _Process.StandardInput.WriteLine("netstat -ano");
            _Process.StandardInput.WriteLine("exit");

            // 获取结果
            Regex reg = new Regex(@"\s+", RegexOptions.Compiled);
            string line = null;
            while ((line = _Process.StandardOutput.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                {
                    line = reg.Replace(line, ",");

                    string[] arr = line.Split(',');
                    if (arr[1].EndsWith(":" + port))
                    {
                        result = KillProcess(Int32.Parse(arr[4]), port);
                        return result;
                    }

                }
            }
            WriteLog.WriteTextLog(null, string.Format("本机 {0}端口 未被占用,服务执行完毕 执行完毕。", port), "");
            return result;
        }

        static int KillProcess(int processName, int port) //调用方法，传参
        {
            int result = 0;
            //    //  Process[] thisproc = Process.GetProcessesByName(processName);
            Process thisproc = Process.GetProcessById(processName);
            try
            {
                if (!thisproc.CloseMainWindow()) //尝试关闭进程 释放资源
                {
                    thisproc.Kill(); //强制关闭
                }
                result = 1;
                WriteLog.WriteTextLog(null, string.Format("本机 {0}端口 进程 {1} 结束成功。", port, thisproc.ProcessName), "");
            }
            catch (Exception ex) //出现异常，表明 kill 进程失败
            {
                WriteLog.WriteTextLog(ex, string.Format("本机 {0}端口 进程 {1} 结束失败。", port, thisproc.ProcessName), "");
            }
            finally
            {
                WriteLog.WriteTextLog(null, string.Format("本机 终止 {0}端口  进程 {1} 服务执行完毕。", port, thisproc.ProcessName), "");
            }
            return result;
        }
    }
}
